package com.hww.common.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.Window;

import androidx.annotation.NonNull;

import com.hww.common.util.ActivityUtils;
import com.hww.common.util.ThreadUtils;

public abstract class BaseDialog extends Dialog {

    protected Activity mActivity;

    public abstract int bindLayout();

    public abstract void initView(BaseDialog dialog, View contentView);

    public abstract void setWindowStyle(Window window);

    public BaseDialog(@NonNull Context context) {
        this(context, 0);
    }

    public BaseDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        Activity activity = ActivityUtils.getActivityByContext(context);
        if (activity == null) {
            throw new IllegalArgumentException("context is not instance of Activity.");
        }
        mActivity = activity;

        View contentView = View.inflate(mActivity, bindLayout(), null);
        setContentView(contentView);
        initView(this, contentView);
        setWindowStyle(getWindow());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void show() {
        ThreadUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (ActivityUtils.isActivityAlive((getContext()))) {
                    BaseDialog.super.show();
                }
            }
        });
    }

    @Override
    public void dismiss() {
        ThreadUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (ActivityUtils.isActivityAlive(getContext())) {
                    BaseDialog.super.dismiss();
                }
            }
        });
    }

    /**
     * 设置对话框关闭的方式
     *
     * @param cancel  设置对话框是否可以通过按返回键（Back键）来关闭
     * @param outside 设置点击对话框外部区域是否关闭对话框
     */
    public void setCancelable(boolean cancel, boolean outside) {
        /*设置对话框是否可以通过按返回键（Back键）来关闭  true 表示可以通过按返回键（Back键）来关闭  false 表示不可以通过按返回键（Back键）来关闭*/
        super.setCancelable(cancel);
        /*设置点击对话框外部区域是否关闭对话框  true 表示点击外部区域关闭对话框  false 表示点击外部区域不关闭对话框*/
        super.setCanceledOnTouchOutside(outside);
    }


}